package it.controllocredito.frontend.util;

import java.util.ArrayList;

import it.controllocredito.R;
import it.controllocredito.backend.persistence.bean.RegistroChiamate;
import android.content.Context;
import android.provider.CallLog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class RegistroChiamateArrayAdapter extends
		ArrayAdapter<RegistroChiamate> {
	private final Context context;
	private final ArrayList<RegistroChiamate> values;

	public RegistroChiamateArrayAdapter(Context context,
			ArrayList<RegistroChiamate> values) {
		super(context, R.layout.rowlayout, values);
		this.context = context;
		this.values = values;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		LayoutInflater inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View rowView = inflater.inflate(R.layout.rowlayout, parent, false);

		//contact img
		if(values.get(position).getList_image() != null){
			ImageView imageView = (ImageView) rowView.findViewById(R.id.list_image);
	        imageView.setImageBitmap(values.get(position).getList_image());
		}
		
		TextView textNumTel = (TextView) rowView.findViewById(R.id.numTel);
		textNumTel.setText(values.get(position).getNumeroTel());

		TextView textDate = (TextView) rowView.findViewById(R.id.date);
		textDate.setText(values.get(position).getGiorno() + "/"
				+ String.valueOf(values.get(position).getMese() + 1) + "/"
				+ values.get(position).getAnno() + " - "
				+ values.get(position).getOra().toString());

		TextView textDuration = (TextView) rowView.findViewById(R.id.duration);
		textDuration.setText(formatDuration(values.get(position).getDurata()));

		String type = "";
		switch (values.get(position).getTipo()) {
		case CallLog.Calls.OUTGOING_TYPE:
			type = "Chiamata in uscita";
			break;

		case CallLog.Calls.INCOMING_TYPE:
			type = "Chiamata in entrata";
			break;

		case CallLog.Calls.MISSED_TYPE:
			type = "Chiamata persa";
			break;

		default:
			type = "Chiamata annullata";
		}

		TextView callType = (TextView) rowView.findViewById(R.id.calltype);
		callType.setText(type);

		return rowView;
	}

	private String formatDuration(long seconds) {
		String rHours = fill(String.valueOf(seconds / 3600), 2, "0");
		String rMinutes = fill(String.valueOf((seconds % 3600) / 60), 2, "0");
		String rSeconds = fill(String.valueOf(seconds % 60), 2, "0");
		return rHours + ":" + rMinutes + ":" + rSeconds;
	}

	private String fill(String str, int width, String filler) {
		if (str.length() > width) {
			return str.substring(0, width);
		} else {
			while (str.length() < width) {
				str = filler + str;
			}
			return str;
		}

	}

}
